package com.study.spmongodb.wwj.juc.atomic;

/**
 * @author study
 * @version 1.0
 * @date 2020/12/11 14:03
 */
public class AtomicIntegerDetailTest2 {

    private final static CompareAndSetLock lock = new CompareAndSetLock();

    public static void main(String[] args) {
        for (int i = 0; i < 5; i++) {
            new Thread(() -> {
                try {
                    doSomething2();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }).start();
        }

    }

    private static void doSomething2() throws Exception {
        try {
            lock.tryLock();
            System.out.println(Thread.currentThread().getName() + " get the lock");
            Thread.sleep(10000);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    private static void doSomething() throws InterruptedException {
        synchronized (AtomicIntegerDetailTest2.class) {
            System.out.println(Thread.currentThread().getName() + " get the lock");
            Thread.sleep(10000);
        }
    }
}
